﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;

namespace _批量插入上万条数据
{
    class Program
    {
        static void Main(string[] args)
        {
            #region 数据构建
            Random rd = new Random();


            List<Person> persons = new List<Person>();
            for (int i = 1; i < 100000; i++)
            {

                int year = rd.Next(20, 31);
                int month = rd.Next(1, 13);
                int day = rd.Next(1, 32);
                if (month == 2)
                {
                    if ((DateTime.Now.Year - year) % 400 == 0 || ((DateTime.Now.Year - year) % 4 == 0 && (DateTime.Now.Year - year) % 100 != 0))
                    {
                        day = rd.Next(1, 30);
                    }
                    else
                    {
                        day = rd.Next(1, 29);
                    }
                }

                Person p = new Person();

                p.PersonCode = "L" + i.ToString().PadLeft(6, '0');
                p.Sex = rd.Next(0, 2);
                p.Birthday = ((DateTime.Now.Year - year) + "-" + month + "-" + day).ToDateTime();
                p.Name = CreateName.GetRandomLastName() + CreateName.GetRandomChinese(2);
                while (true)
                {
                    if (persons.Select(x => x.Name).Contains(p.Name))
                    {
                        p.Name = CreateName.GetRandomLastName() + CreateName.GetRandomChinese(2);
                    }
                    else
                    {
                        break;
                    }
                }
                p.CreateDate = DateTime.Now;
                p.CreateBy = 1;
                persons.Add(p);

            }

            DataTable dt = persons.ToDateTable();
            #endregion

            //批量插入数据方式一 SQLBulkCopy
            SqlUtil.InsertMassData(SqlUtil.ConnString, dt, "Person");

            //批量插入数据方式 存储过程参数形式
            //需要使用SQL Server 用户自定义表类型
            //SqlParameter param = new SqlParameter("@PersonTable", SqlDbType.Structured);
            //param.Value = dt;
            //int result = SqlUtil.ExecutionSql(SqlUtil.ConnString, "Proc_InsertPersonData", CommandType.StoredProcedure, param);

            Console.ReadKey();

        }
    }
}
